<template>
  <div class="product-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">本地的特色美食</h1>
      <p class="page-subtitle">发现我们的美味佳肴</p>
    </div>

    <!-- 搜索和排序控件 -->
    <div class="controls-section">
      <div class="search-container">
        <el-input v-model="searchQuery" placeholder="搜索美食...">
          <template #append>
            <el-icon @click="handleSearch" style="cursor: pointer"><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="sort-container">
        <el-select v-model="sortBy" placeholder="选择排序" clearable @change="handleFilter">
          <el-option label="默认排序" value="-1" />
          <el-option label="价格从低到高" value="1" />
          <el-option label="价格从高到低" value="2" />
          <el-option label="名称排序" value="3" />
          <el-option label="评分最高" value="4" />
        </el-select>
      </div>
    </div>

    <section class="product-list" v-loading="loading">
      <el-empty v-if="list.length == 0" description="暂无数据" />
      <div v-for="(item, index) in list" :key="item.id" class="product-item">
        <RouterLink :to="`/product/detail?id=${item.id}`" target="_blank">
          <div class="image-container">
            <img :src="item.image" :alt="item.name" class="product-image" />
            <div v-if="!item.isEnabled" class="unavailable-overlay">
              <span>已售罄</span>
            </div>
          </div>
          <div class="product-content">
            <div class="header-section">
              <h2 class="product-name">{{ item.name }}</h2>
              <div class="rating">
                <span class="stars">
                  <el-rate v-model="item.rating" />
                </span>
                <span class="rating-value">{{ item.rating }}分</span>
              </div>
            </div>
            <p class="product-description">{{ item.description }}</p>
            <div class="category-tag">{{ item.origin }}</div>
            <div class="tags">
              <span v-for="tag in JSON.parse(item.tagsJson)" :key="tag" class="tag">{{ tag }}</span>
            </div>
            <div class="footer-section">
              <p class="product-price">{{ formatCurrency(item.price) }}</p>
              <div>
                <el-popconfirm title="你确定删除该数据" @confirm="handleRemove(item)" placement="top">
                  <template #reference>
                    <el-button type="warning" v-if="showAdminOpts" plain> 删除 </el-button>
                  </template>
                </el-popconfirm>
                <button :disabled="!item.isEnabled" v-if="false" class="order-button" :class="{ disabled: !item.isEnabled }">
                  {{ item.isEnabled ? '立即订购' : '已售罄' }}
                </button>
              </div>
            </div>
          </div>
        </RouterLink>
      </div>
    </section>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background layout="prev, pager, next" :page-size="10" :total="totalCount" @change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue'
import { useHead } from '@vueuse/head'
import { fetchList, remove } from '@/apis/product'
import { Search } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
const userStore = useUserStore()

const router = useRouter()

useHead({
  title: '地方特产 - 本地特色美食',
  meta: [
    { name: 'description', content: '探索本地的特色美食，发现独特的风味和文化。' },
    { name: 'keywords', content: '特产, 美食, 地方特色, 订购' }
  ]
})

const showAdminOpts = computed(() => {
  return userStore.showAdminOpts ?? false
})

const handleRemove = (obj: any) => {
  // 处理删除逻辑
  remove(obj.id)
    .then((response) => {
      let { code, message } = response.data
      if (code !== 200) {
        throw new Error(message || '删除失败')
      }
      // 删除成功后重新获取数据
      fetchData()
    })
    .catch((error) => {
      console.error('删除失败:', error)
    })
}

const totalCount = ref(0) // 假设总职位数为1000
const searchQuery = ref('') // 搜索关键词
const listQuery = {
  page: 1,
  pageSize: 12,
  keyword: ''
}
const list = reactive<any>([])

const loading = ref(false)
const fetchData = () => {
  // 模拟获取数据
  listQuery.keyword = searchQuery.value.trim()
  loading.value = true
  fetchList(listQuery)
    .then((response) => {
      let { code, result, message } = response.data
      if (code !== 200) {
        throw new Error(message || '获取数据失败')
      }
      if (result.page) {
        list.splice(0, list.length) // 清空列表
      }
      totalCount.value = result.total
      for (let item of result.items) {
        let imgs = JSON.parse(item.imageUrls)
        item.image = imgs.length > 0 ? imgs[0] : 'https://picsum.photos/400/300?ght=200&width=300'
      }
      list.splice(0, 0, ...result.items)
      // console.log('获取到的数据:', list)
    })
    .catch((error) => {
      console.error('获取数据失败:', error)
    })
    .finally(() => {
      loading.value = false
    })
}

const handleCurrentChange = (page: number, pageSize: number) => {
  // 这里可以添加分页逻辑
  listQuery.page = page
  listQuery.pageSize = pageSize
  fetchData()
  // console.log(`当前页: ${page}, 每页条数: ${pageSize}`)
}

onMounted(() => {
  fetchData()
})

const handleFilter = () => {
  // 处理搜索和排序
  fetchData()
}

const handleSearch = () => {
  // 处理搜索和排序
  fetchData()
}

// 搜索和排序相关的响应式变量
const sortBy = ref('-1')

// 格式化货币
const formatCurrency = (value: number): string => {
  return `￥${value.toFixed(2)}`
}
</script>

<style scoped>
.product-page {
  padding: 20px;
  max-width: var(--page-max-width);
  background-color: #f8fafc;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 32px;
}

.page-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #2563eb;
  margin-bottom: 8px;
  font-family: 'Space Grotesk', sans-serif;
}

.page-subtitle {
  font-size: 16px;
  color: #64748b;
  font-family: 'DM Sans', sans-serif;
}
.controls-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  gap: 20px;
  flex-wrap: wrap;
}

.search-container {
  flex: 1;
  min-width: 200px;
}

.search-input {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #4caf50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.sort-container {
  min-width: 150px;
}

.sort-select {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  background: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.sort-select:focus {
  outline: none;
  border-color: #4caf50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.product-header {
  text-align: center;
  margin-bottom: 30px;
}

.product-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1.1rem;
  color: #666;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
}

.product-item {
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  cursor: pointer;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease;
  background: white;
}

.product-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.image-container {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-item:hover .product-image {
  transform: scale(1.05);
}

.unavailable-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 1.2rem;
}

.product-content {
  padding: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.product-name {
  font-size: 1.4rem;
  font-weight: 600;
  color: #333;
  margin: 0;
  flex: 1;
}

.rating {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: flex-end;
}

.rating-value {
  font-size: 0.9rem;
  color: #666;
  margin-top: 2px;
}

.product-description {
  font-size: 0.95rem;
  color: #555;
  line-height: 1.5;
  margin-bottom: 15px;
  display: -webkit-box;
  color: #555;
  -webkit-line-clamp: 4; /* 限制2行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.category-tag {
  display: inline-block;
  background: #e3f2fd;
  color: #1976d2;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 500;
  margin-bottom: 15px;
}

.tags {
  margin-bottom: 20px;
}

.tag {
  display: inline-block;
  background: #f5f5f5;
  color: #666;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 0.75rem;
  margin-right: 5px;
  margin-bottom: 5px;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.product-price {
  font-size: 1.3rem;
  font-weight: 700;
  color: #e53935;
  margin: 0;
}

.order-button {
  background: #4caf50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  margin-left: 10px;
  transition: background 0.3s ease;
}

.order-button:hover:not(.disabled) {
  background: #43a047;
}

.order-button.disabled {
  background: #bdbdbd;
  cursor: not-allowed;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
</style>
